// miniprogram/packageAdmin/pages/index/index.js
import {getDate} from "../../../utils/Util";
import Static from "../../../utils/Static";
import {getStorageSync, removeStorageSync} from "../../../utils/Storage";
import {deleteRecord, updateRecord} from "../../../service/Record";
import {sendMessage} from "../../../service/Open";
import Dialog from "@vant/weapp/dialog/dialog";
import Toast from "@vant/weapp/toast/toast";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        loadList: {
            useSlot: false,
            params: {},
            loading: false,
            reset: false,
            list: []
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({"loadList.loading": true})
    },

    /*
    * 筛选组件监听函数
    * */
    onScreen: function (e) {
        let params = e.detail.result;
        this.setData({
            "loadList.params": params,
            "loadList.reset": true //重置数据
        })
    },

    /*
     * 列表加载组件
     * */
    onLoadList: function (e) {
        const that = this;
        let success = e.detail.success;
        let list = that.data.loadList.list,
            isReset = that.data.loadList.reset;
        if (success) {
            let newList = e.detail.result.map(function (item) {
                item.createTime = getDate(item.createTime).split(" ")[0];
                item.delLoading = false; //删除加载动画
                item.completeLoading = false; //完成加载动画
                return item
            });
            !isReset ? list.push.apply(list, newList) : list = newList;
            that.setData({
                ["loadList.list"]: list,
                ["loadList.reset"]: false,
                ["loadList.useSlot"]: list.length === 0
            })
            that.___refreshController = true;
        }
    },

    /*
     * 点击按钮
     * */
    bindClick: async function (e) {
        let isManager = getStorageSync("userInfo.isManager");
        let todo = e.currentTarget.dataset.todo;
        let index = e.currentTarget.dataset.index;
        let list = this.data.loadList.list;
        let id = list[index]._id;
        if (!isManager) { //不是管理员
            Dialog.alert({
                title: "非法登录",
                message: "您不是管理员，请退出该页面",

            })
            return false
        }
        switch (todo) {
            case "delete":
                try {
                    await Dialog.confirm({
                        title: "提示",
                        message: "是否删除该条信息",
                    })
                    this.setData({["loadList.list[" + index + "].delLoading"]: true})
                    await deleteRecord(id);
                    list.splice(index, 1);
                    this.setData({
                        ["loadList.list"]: list,
                        ["loadList.useSlot"]: list.length === 0
                    })
                } catch (e) {
                    Toast.fail("删除失败");
                    this.setData({["loadList.list[" + index + "].delLoading"]: false});
                    console.error(e)
                }
                break
            case "verify":
                try {
                    let currentData = this.data.loadList.list[index];
                    let templateId = Static.templateId.shtz;
                    let verify = currentData.verify !== 2 ? 2 : 1;
                    this.setData({["loadList.list[" + index + "].verifyLoading"]: true})
                    await updateRecord(id, {verify: verify});
                    this.setData({
                        ["loadList.list[" + index + "].verify"]: verify,
                        ["loadList.list[" + index + "].verifyLoading"]: false
                    })
                    if (currentData[templateId] > 0) {
                        await sendMessage({
                            openId: currentData.openId,
                            page: "pages/user/record-detail/record-detail?id=" + currentData._id,
                            data: {
                                phrase1: {
                                    value: verify === 1 ? "通过" : "不通过",
                                    color: verify === 1 ? "" : "#ff4d59"
                                },
                                thing2: {
                                    value: currentData.intro || (currentData.type === "lost" ? "发布寻丢消息" : "发布还拾消息")
                                },
                                date4: {
                                    value: getDate(currentData.createTime).split(" ")[0]
                                },
                                date3: {
                                    value: getDate(new Date().getTime()).split(" ")[0]
                                }
                            },
                            templateId: templateId,
                            miniprogramState: Static.config.miniprogramState
                        })
                        await updateRecord(currentData._id, {
                            [templateId]: currentData[templateId] - 1
                        })
                        this.setData({
                            ["loadList.list[" + index + "]." + templateId]: currentData[templateId] - 1
                        })
                    }
                } catch (e) {
                    Toast.fail("修改状态失败");
                    this.setData({["loadList.list[" + index + "].verifyLoading"]: false});
                    console.error(e)
                }
                break
            case "complete":
                try {
                    this.setData({["loadList.list[" + index + "].completeLoading"]: true})
                    await updateRecord(id, {complete: 1});
                    this.setData({["loadList.list[" + index + "].complete"]: 1})
                } catch (e) {
                    Toast.fail("更新状态失败");
                    this.setData({["loadList.list[" + index + "].completeLoading"]: false});
                    console.error(e)
                }
                break
            case "detail":
                wx.navigateTo({
                    url: "/pages/user/record-detail/record-detail?id=" + id
                })
                break
        }
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        if (this.___refreshController) {
            this.___refreshController = false;
            this.setData({["loadList.reset"]: true});
            setTimeout(function () {
                wx.stopPullDownRefresh();
            }, 1500)
        } else {
            wx.stopPullDownRefresh();
        }
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        this.setData({["loadList.loading"]: true})
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {}
})